package echat.future.cn.echat.my.view;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaMetadataRetriever;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.view.View;
import android.view.ViewAnimationUtils;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.zhusx.core.network.HttpRequest;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import echat.future.cn.echat.R;
import echat.future.cn.echat.databinding.ActivityMyVideoBinding;
import echat.future.cn.echat.my.adapter.VideoAdapter;
import echat.future.cn.echat.my.api.UserApi;
import echat.future.cn.echat.my.bean.ImageBean;
import echat.future.cn.echat.my.bean.MyViedio;
import echat.future.cn.echat.my.bean.VideoBean;
import echat.future.cn.echat.my.utils.HttpUtilsRequst;
import echat.future.cn.echat.my.utils.ImageLoadUtils;
import echat.future.cn.echat.my.utils.UserHelper;
import echat.future.cn.echat.my.weight.Navagation.AdapterNavagation;
import echat.future.cn.echat.my.weight.Navagation.IBaseNavagation;
import echat.future.cn.echat.my.weight.dialog.ChoosePicDialog;
import echat.future.cn.echat.my.weight.dialog.ChoseDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 我的视频
 */
public class MyVideoActivity extends BaseActivity<ActivityMyVideoBinding>{

    /**
     * 免费视频
     */
    private final int EXTRA_TYPE_FREE = 1;

    /**
     * 收费视频类型
     */
    private final int EXTRA_TYPE_CHARGE = 2;


    /**
     * 当前选中类型，根据他切换UI以及加载数据
     */
    private int currentType = EXTRA_TYPE_FREE;

    /**
     * 选择视频弹出框
     */
    Dialog choosePicDialog;


    /**
     * 免费视屏适配器
     */
    VideoAdapter freeAdapter;

    /**
     * 免费视屏数据源
     */
    List<ImageBean> freeDatas = new ArrayList<>();




    /**
     * 收费视屏适配器
     */
    VideoAdapter chargeAdapter;

    /**
     * 收费视屏数据源
     */
    List<ImageBean> chargeDatas = new ArrayList<>();

    @Override
    public int layoutId() {
        return R.layout.activity_my_video;
    }

    @Override
    public IBaseNavagation navagation() {
        return new AdapterNavagation(this).setTitle("我的小视频",
                16, R.color.white).setBack(R.drawable.btn_back).setNavagationBackgroudColor(R.color.color_161823);
    }

    @Override
    public void initView() {

        //初始化默认数据
        freeDatas.add(new ImageBean());
        chargeDatas.add(new ImageBean());

        //初始化适配器
        freeAdapter = new VideoAdapter(this.freeDatas);
        chargeAdapter = new VideoAdapter(this.chargeDatas);
        //初始化recylerview
        bind.recyclerFree.setLayoutManager(new GridLayoutManager(this,3));
        bind.recyclerCharge.setLayoutManager(new GridLayoutManager(this,3));
        bind.recyclerFree.setAdapter(freeAdapter);
        bind.recyclerCharge.setAdapter(chargeAdapter);
        //点击时间
        freeAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if(view.getId() == R.id.add){
                showChooseDialog();
            }
            if(view.getId() == R.id.delete){
                deleteVideo(position);
            }
        });

        chargeAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if(view.getId() == R.id.add){
                showChooseDialog();
            }
            if(view.getId() == R.id.delete){
                deleteVideo(position);
            }
        });
        bind.free.setOnClickListener(v -> {
            currentType = EXTRA_TYPE_FREE;
            show();
        });
        bind.charge.setOnClickListener(v -> {
            currentType = EXTRA_TYPE_CHARGE;
            show();
        });
        show();
        getMyViedio();
    }


    Dialog deleteDialog = null;
    /**
     * 删除视屏
     */
    private void deleteVideo(int position){
        deleteDialog=  new ChoseDialog.Builder(this).content("确定删除视频么？\n" +
                    "此操作不可恢复。")
                    .rightListener(v->{
                        if(currentType == EXTRA_TYPE_CHARGE){
                            deleteViedio(chargeDatas.get(position).getId());
                        }else{
                            deleteViedio(freeDatas.get(position).getId());
                        }
                        deleteDialog.dismiss();
                    }).Builder();
        deleteDialog.show();
    }

    private void show(){
        if(currentType == EXTRA_TYPE_FREE){
            bind.free.setBackgroundResource(R.drawable.bg_6560e2_r5);
            bind.charge.setBackgroundColor(Color.TRANSPARENT);
            bind.recyclerCharge.setVisibility(View.GONE);
            bind.recyclerFree.setVisibility(View.VISIBLE);
            bind.hint.setVisibility(View.GONE);
        }else{
            bind.charge.setBackgroundResource(R.drawable.bg_6560e2_r5);
            bind.free.setBackgroundColor(Color.TRANSPARENT);
            bind.recyclerFree.setVisibility(View.GONE);
            bind.recyclerCharge.setVisibility(View.VISIBLE);
            bind.hint.setVisibility(View.VISIBLE);
        }
    }


    private void showChooseDialog(){
        if(choosePicDialog == null){
            choosePicDialog = new ChoosePicDialog.Builder(this)
                    .content("请选择视频来源")
                    .photoString("拍摄")
                    .photoListenter(v -> choosePic())
                    .cameroListenter(v ->chooseCamero()).Builder();
        }
        choosePicDialog.show();
    }



    private void choosePic() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofVideo())
                .maxSelectNum(1)
                .isCamera(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
        if(choosePicDialog!=null)
            choosePicDialog.dismiss();
    }


    private void chooseCamero() {
        PictureSelector.create(this).openCamera(PictureMimeType.ofVideo())
                .maxSelectNum(1)
                .isCamera(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);
        if(choosePicDialog!=null)
            choosePicDialog.dismiss();
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 图片选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                for(int i=0;i<selectList.size();i++) {
                    LocalMedia media = selectList.get(i);
                    String headImgPath = "";
                    if (media.isCut()) {
                        headImgPath = media.getCutPath();
                    } else {
                        headImgPath = media.getPath();
                    }
                    uploadViedio(headImgPath);
//                    if(currentType == EXTRA_TYPE_FREE){
//                        freeDatas.add(freeDatas.size()-1,new ImageBean(headImgPath));
//                        freeAdapter.notifyDataSetChanged();
//                    }else{
//                        chargeDatas.add(chargeDatas.size()-1,new ImageBean(headImgPath));
//                        chargeAdapter.notifyDataSetChanged();
//                    }
                }
            }
        }
    }





    private void getMyViedio(){
        new HttpUtilsRequst<MyViedio>(this,HttpUtilsRequst.retrofitClient.create(UserApi.class).getOwnViedio(UserHelper.getToken()))
                .setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<MyViedio>) myViedio -> {
                    freeDatas.clear();
                    chargeDatas.clear();
                    freeDatas.add(new ImageBean());
                    chargeDatas.add(new ImageBean());

                    for (VideoBean v:myViedio.getFree_video()){
                        freeDatas.add(viedio2ImageBean(v));
                    }

                    for (VideoBean v:myViedio.getPay_video()){
                        chargeDatas.add(viedio2ImageBean(v));
                    }
                    if(currentType == EXTRA_TYPE_FREE){
                        freeAdapter.notifyDataSetChanged();
                    }else{
                        chargeAdapter.notifyDataSetChanged();
                    }
                })
                .start();
    }


    private ImageBean viedio2ImageBean(VideoBean videoBean){
        ImageBean imageBean = new ImageBean();
        imageBean.setImg(videoBean.getImg());
        imageBean.setId(videoBean.getId());
        return imageBean;
    }




    private void uploadViedio(String viedo){
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), new File(viedo));
        MultipartBody.Part  partViedoy = MultipartBody.Part.createFormData("video[0]", new File(viedo).getName(), requestBody);

        MediaMetadataRetriever mmr=new MediaMetadataRetriever();//实例化MediaMetadataRetriever对象
        mmr.setDataSource( new File(viedo).getAbsolutePath());//设置数据源为该文件对象指定的绝对路径
        Bitmap bitmap=mmr.getFrameAtTime();//获得视频第一帧的Bitmap对象
        File file = ImageLoadUtils.saveBitMapToFile(this,"cache.png",bitmap,true);
        RequestBody requestBody2 = RequestBody.create(MediaType.parse("image/jpeg"), file);
        MultipartBody.Part  imagePart = MultipartBody.Part.createFormData("img[0]", file.getName(), requestBody2);
        new HttpUtilsRequst<String>(this,HttpUtilsRequst.retrofitClient.create(UserApi.class).upLoadMyViedio(
                UserHelper.getToken(),
                currentType,
                partViedoy,
                imagePart
        )).setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<String>) o -> {
            toast("新增小视频成功");
            getMyViedio();
        }).start();
    }

    public void deleteViedio(int id){
        new HttpUtilsRequst<String>(this,HttpUtilsRequst.retrofitClient.create(UserApi.class).deleteVideo(
                UserHelper.getToken(),
                id
        )).setmOnRequstSuccessListener((HttpUtilsRequst.OnRequstSuccessListener<String>) o -> {
            toast("删除小视频成功");
            getMyViedio();
        })
                .start();
    }

}
